package uit.edu.vn.Activity;

import java.io.File;

import java.io.FileReader;

import java.util.ArrayList;
import java.util.HashMap;

import uit.edu.vn.Contact.MyContact;
import uit.edu.vn.Contact.imContact;

import uit.edu.vn.Model.myFile;
import uit.edu.vn.Utility.Contact;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.xStreamXML;

import android.app.AlertDialog;
import android.app.Dialog;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContactRestoreSDCardActivity extends MyActivity{
	private ListView listview;
	private Context context;
	private Resources res;
	private String path = Environment.getExternalStorageDirectory()+"/BackupManager/Contact";
	private ArrayList<myFile> listFiles = new ArrayList<myFile>();
	private int numberOfItemSelected = 0;
	private ArrayAdapter<myFile> arrayAdapter;
	private ArrayList<MyContact> myContactList;
	private Contact contact;
	private ProgressDialog prg;
	private static ProgressDialog loadingContactDialog;
	private Handler handler;
	private TextView titleHeader;
    private String username = "";
    private String password = "";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.backup_file);
		
        username = getSetting("username");
        password = getSetting("password");
        //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	      if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(ContactRestoreSDCardActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }	
	      System.out.println("path save file:" + path);
			File dir = new File(path);
			dir.mkdirs();
		titleHeader=(TextView)findViewById(R.id.txt_titleFile);
		titleHeader.setText(R.string.title_RestoreHeaderContactSDcard);
		context=getBaseContext();
		contact = new Contact();
		contact.setCr(getContentResolver());
		contact.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
		listview =(ListView)findViewById(R.id.listFileBackup);		
		res=getResources();		
		handler = new Handler();
		prg= new ProgressDialog(this);		
		prg.setCancelable(false);
		prg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		//lay tat ca cac file trong thu muc dua vao list view	
//		prg = showProgress("Đang tải danh sách danh bạ đã sao lưu!", "Đợi trong chốc lát...", R.drawable.ic_lock, false);
		new BackGroundTask().execute();
        listview.setOnItemClickListener(new OnItemClickListener() 
        {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				try {
	     		   	System.out.println("jgyghghg");
								// TODO Auto-generated method stub
	     		   	
								myFile entry = listFiles.get(arg2);
								File temp = new File(entry.getPath());
								final Dialog dialog=new Dialog(ContactRestoreSDCardActivity.this);
				 	    		dialog.setContentView(uit.edu.vn.Activity.R.layout.file_dialog);
				 	    		dialog.setTitle("Thông tin tập tin");
				 	    		TextView txt_filename= (TextView)dialog.findViewById(R.id.txt_nameDialog);
				 	    		TextView txt_filesize= (TextView)dialog.findViewById(R.id.txt_sizeDialog);
				 	    		txt_filename.setText(temp.getName());
				 	    		txt_filesize.setText(String.valueOf(temp.length())+"Kb");
				 	    		
				 	    		Button btn_ok = (Button)dialog.findViewById(R.id.btn_okDialog);
				 	    		btn_ok.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										dialog.dismiss();
									}
								});
				 	    		dialog.show();
							}
					
	     		   	 catch (Exception e) {
						// TODO: handle exception
						  e.printStackTrace();
					}
			}
     	   
        });
	}
	
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	}
	
	public void addToListView(){
		arrayAdapter = new ArrayAdapter<myFile>(this, R.layout.row_file, listFiles) {
            @Override
            public View getView(int position, View v, ViewGroup parent) {
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row_file, null);
                }
                
                myFile file = listFiles.get(position);                
                if(file!=null){
                    TextView tx_fileName = (TextView)v.findViewById(R.id.txt_fileName);
                    TextView tx_size = (TextView)v.findViewById(R.id.txt_filePath);
                    ImageView iv = (ImageView) v.findViewById(R.id.img_fileIcon);
                    iv.setImageDrawable(res.getDrawable(R.drawable.ic_text));
                    
                    CheckBox chkSelect = (CheckBox) v.findViewById(R.id.chkSelectFile);
                    chkSelect.setChecked(false);
                    
                	tx_fileName.setText(file.getName());
                	           	
                	int temp=Integer.parseInt(file.getSize());
                	if(temp<1024)
                	{
                		tx_size.setText(file.getSize()+" Byte");   
                	}
                	else
                	{
                		temp=temp/1024;
                		tx_size.setText(String.valueOf(temp)+" KB"); 
                	}     	
                }
                return v;
            }
		};
		countItemChecked();
        listview.setOnCreateContextMenuListener(this);
        listview.setAdapter(arrayAdapter);
	}
	
    private class BackGroundTask extends AsyncTask<Void, Void, Void>
    {
    	@Override
    	protected void onPreExecute() 
    	{
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    		prg.setMessage("Đang tải dữ liệu");
    		prg.show();
    	}
    	@Override
    	protected Void doInBackground(Void... params) {
    		// TODO Auto-generated method stub
         	getAllFile(path);   	
    		return null;
    	}
    	@Override
    	protected void onPostExecute(Void result) {
    		// TODO Auto-generated method stub
     		if(listFiles == null){
     			prg.dismiss();
     			showToast("Không có tập tin danh bạ sao lưu");     			
     		}else {
                 addToListView();
                 prg.dismiss();
     		} 
    		prg.dismiss();  
    		super.onPostExecute(result);
    	}
    }
	
	//bat su kien click check box o cuoi moi dong
	public void CheckButtonOnClick(View v){
		
		CheckBox chk = (CheckBox) v;
		int position = listview.getPositionForView(v);
		myFile file = arrayAdapter.getItem(position);
		file.setChecked(chk.isChecked());
		numberOfItemSelected += chk.isChecked() ? 1 : -1;
	}
	
	
    private void countItemChecked() {
        numberOfItemSelected = 0;
        for (int i = 0; i < listFiles.size(); i++) {
            if (listFiles.get(i).getChecked()) {
                numberOfItemSelected++;
            }
        }
    }
    
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    	// TODO Auto-generated method stub	    	
		new MenuInflater(getApplicationContext()).inflate(R.menu.restore_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    	// TODO Auto-generated method stub
	    switch(item.getItemId()){
	    	case R.id.menu_restore_File:	 
	    		int flag=0;
				for(int i=0;i<listFiles.size();i++)
				{
					if(listFiles.get(i).getChecked()==true)
					{
						flag=1;
						numberOfItemSelected++;
					}
				
				}
				if(flag==0)
				{
					numberOfItemSelected=0;
				}
    			if(numberOfItemSelected==0)
    			{
    				showToast("Vui lòng chọn danh bạ cần phục hồi");
    			}
    			else
            	{
    				new AsyncTask<Void, Void, Void>()
            	
            	{
            		@Override
            		protected void onPreExecute() {
            			// TODO Auto-generated method stub            			
            			super.onPreExecute();
            			prg.setMessage("Đang phục hồi danh bạ");
            			prg.show();
            		}
            		@Override
            		protected Void doInBackground(Void... params) 
            		{  
            			// TODO Auto-generated method stub            			
            			String result = restoreContact();
            			if(result.equals("0")){
            				prg.dismiss();
            				showToast("Phục hồi danh bạ không thành công");
            			}
            			return null;
            		}
            		@Override
            		protected void onPostExecute(Void result)
            		{
            			// TODO Auto-generated method stub
            			super.onPostExecute(result);
    		    		arrayAdapter.notifyDataSetChanged();            			
            			prg.dismiss();
            		       new AlertDialog.Builder(ContactRestoreSDCardActivity.this).setMessage("Phục hồi danh bạ thành công! ").setTitle(getResources().getString(R.string.dialog_thongbao)).setPositiveButton("Kết Thúc", new OnClickListener() {
			                    public void onClick(DialogInterface dialog, int which) {
			
			                    }                   
		                    }).show();
            		}
            	
            	}.execute();	    		
            	}
	    		return true;
	    
	    	case R.id.menu_restore_Delete:
	    			// duyet mang file de xem file nào đc check
	    			// xong xóa file theo tên file
	    		int flag1=0;
				for(int i=0;i<listFiles.size();i++)
				{
					if(listFiles.get(i).getChecked()==true)
					{
						flag1=1;
						numberOfItemSelected++;
					}
				
				}
				if(flag1==0)
				{
					numberOfItemSelected=0;
				}
    			if(numberOfItemSelected==0)
    			{
    				showToast("Vui lòng chọn danh bạ cần xóa");
    			}
    			else
    			{	showConfirmDialog("Cảnh Báo", "Bạn muốn xóa tập tin này?","", new OnClickListener() {
					private int total = 0;
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						for(int i=0;i<listFiles.size();i++)
		    			{
							myFile mfile = listFiles.get(i);
		    				if(mfile.getChecked()==true)
		    				{
		    					File temp= new File(listFiles.get(i).getPath());
		    					listFiles.remove(mfile);
		    					temp.delete();	
		    					numberOfItemSelected--;
		    					i--;
		    				}
		    			}
						//thong báo xóa file thành công
						new AlertDialog.Builder(ContactRestoreSDCardActivity.this).setMessage("Xóa Tập Tin Thành Công!")
						.setIcon(R.drawable.ic_info_select).setTitle("Thông Báo!").setPositiveButton("Kết thúc", new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								//duyet mang và set check lai false
								arrayAdapter.notifyDataSetChanged();
								dialog.cancel();
							}
						}).show();
		    			
					}
	    			});
	    			
    			}
	    			return true;
	    	case R.id.menu_restore_Logout:
	    		logOut();
                Intent intent = new Intent(ContactRestoreSDCardActivity.this, LoginActivity.class);
                startActivity(intent);
                this.finish();
    			return true;		
	    			
	    }
	    return false;
	}

	private void getAllFile(String path)
	{
		try
		{
			//lay duong dan cua folder chua file restore
			File f= new File(path);
			File[] files= f.listFiles();
			for(int i=0; i<files.length;i++)
			{
				File file = files[i];
				listFiles.add(new myFile(file.getName(),file.getPath(), String.valueOf(file.length()), res.getDrawable(R.drawable.ic_file_selector)));
			}
		}
		catch(Exception e)
		{
			
			e.printStackTrace();
		}
	}
	private String restoreContact(){
		try{
    		myFile file = null;
    		for(myFile mfile:listFiles){
				if(mfile.getChecked()){
					file = mfile;
				}			
				mfile.setChecked(false);
    		}	                		    			                		    		
    		File fileRestore = new File(file.getPath());
    		FileReader filereader = new FileReader(fileRestore);
			myContactList = xStreamXML.fromXML(filereader);
			for(int i = 0; i<myContactList.size(); i++){
				MyContact mcontact = myContactList.get(i);
				contact.writeContact(mcontact);				
			}
			for(myFile mfile:listFiles)		
				mfile.setChecked(false);
			return "1";
	                		    			        		    			
		}catch(Exception ex){
    		System.out.println("loi khi import contact sdcard2:  " + ex.toString());    
    		return "0";
		}
		
	}
	
	 public AlertDialog showConfirmDialog(String title, String msg,String fileName, OnClickListener yesClick) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.ic_error);
			if(title!=null) builder.setTitle(title);
			if(msg!=null) builder.setMessage(msg);
			return builder.setPositiveButton("Yes", yesClick).setNegativeButton("No", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
	}
	 
 	public ProgressDialog showProgress(String title, String msg, int icon, boolean cancelable) {
		ProgressDialog pdialog = new ProgressDialog(this);
		if (title != null) {
			pdialog.setTitle(title);
		}
		if (msg != null)
			pdialog.setMessage(msg);
		if (icon != -1) {
			pdialog.setIcon(icon);
		}
		pdialog.setCancelable(cancelable);
		pdialog.show();
		return pdialog;
	}
 	

}
